<?php

namespace app\jigou\controller\qingdongams\customer;

use addons\qingdongams\model\Contract;
use addons\qingdongams\model\Customer;
use addons\qingdongams\model\Form;
use addons\qingdongams\model\Staff;
use app\jigou\controller\qingdongams\Base;
use app\common\controller\Backend;
use think\Db;
use think\Exception;

/**
 * 回款计划
 *
 * @icon fa fa-circle-o
 */
class Receivablesplan extends Base
{
    
    /**
     * Receivablesplan模型对象
     * @var \addons\qingdongams\model\ReceivablesPlan
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \addons\qingdongams\model\ReceivablesPlan();

    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //0:全部 1：我负责的 2：下属负责的
            $type = input('type',0);
            switch($type){
                case 1:
                    $staff = Staff::info();
                    $wheres['owner_staff_id'] =  $staff->id;
                    break;
                case 2:
                    $wheres['owner_staff_id'] =  array('in',Staff::getLowerStaffId());
                    break;
                default:
                    $wheres['owner_staff_id'] =  array('in',Staff::getMyStaffIds());
                    break;

            }
            $list = $this->model
                    ->with(['createStaff','ownerStaff','customer','contract'])
                    ->where($where)
                    ->where($wheres)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','num','receivables_id','status','contract_id','customer_id','money','return_date','return_type','remind','remind_date','remarks','create_staff_id','owner_staff_id','createtime','updatetime']);
                $row->visible(['customer','contract']);
                $row->create_staff_id=$row['create_staff']['name'];
                $row->owner_staff_id=$row['owner_staff']['name'];
                $row->customer_id=$row['customer']['name'];
                $row->contract_id=$row['contract']['name'];
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加回款计划
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');

            if (($result = $this->qingdongamsValidate($params, 'ReceivablesPlan', 'create')) !== true) {
                $this->error($result);
            }
            if ($this->model::where([
                'num'         => $params['num'],
                'contract_id' => $params['contract_id']
            ])->find()) {
                $this->error('计划回款期数已存在');
            }

            Db::startTrans();
            try {
                $this->model::createPlan($params);

                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result) {
                $this->success('新增回款计划成功');
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $customer_id= input('customer_id');
        $contract_id= input('contract_id');
        $this->assign('customer_id',$customer_id);
        $this->assign('contract_id', $contract_id);
        $this->assign('customer', Customer::get($customer_id));
        $this->assign('contract', Contract::get($contract_id));
        $this->assign('customer_id', input('customer_id'));
        $this->assign('createnum',get_num('receivablesplan'));
        return $this->view->fetch();
    }
    /**
     * 修改回款计划
     */
    public function edit($ids=null)
    {
        $map['id'] = $ids;
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');

            if (($result = $this->qingdongamsValidate($params, 'ReceivablesPlan', 'create')) !== true) {
                $this->error($result);
            }
            if (!$this->model::where($map)->find()) {
                $this->error('计划回款不存在');
            }
            if ($this->model::where([
                'num'         => $params['num'],
                'contract_id' => $params['contract_id'],
                'id'=>['neq',$ids]
            ])->find()) {
                $this->error('计划回款期数已存在');
            }

            Db::startTrans();
            try {
                $this->model::updatePlan($map,$params);

                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result) {
                $this->success('修改回款计划成功');
            }
            $this->error('修改失败');
        }
        $row = $this->model->where($map)->with(['contract','customer'])->find();
        $this->assign('row',$row);
        $this->assign('createnum',get_num('receivablesplan'));
        return $this->view->fetch();
    }
    /**
     * 获取客户列表
     */
    public function getcustomer()
    {
        $pageSize = input('pageSize');
        $pageNumber = input('pageNumber');
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = $keyValue;
        }
        $name = input('name');
        if (!empty($name)) {
            $where['name'] = ['like', '%' . $name . '%'];
        }
        $staff = Staff::info();
        $staff_id = $staff->id;
        $whereStaff = function ($query) use ($staff_id) {
            $query->where(['ro_staff_id' => ['like', "%,{$staff_id},%"]])
                ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
                ->whereOr(['owner_staff_id' => ['in', Staff::getMyStaffIds()]]);
        };
        $customer = Customer::where($whereStaff)->where($where)->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
        return json(['list' => $customer->items(), 'total' => $customer->total()]);
    }

    /**
     * 获取订单
     */
    public function getcontract()
    {
        $pageSize = input('pageSize');
        $pageNumber = input('pageNumber');
        $customer_id = input('customer_id', 0);
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = $keyValue;
        }
        $name       = input('name');
        if(!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $where['customer_id'] = $customer_id;
        $where['check_status'] = 2;
        $contacts = Contract::where($where)->field('id,name,num')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
        $data = [];
        $item=$contacts->items();
        foreach ($item as $v) {
            $v->name=$v['num'] . "（{$v['name']}）";
        }
        return json(['list' => $item, 'total' =>$contacts->total()]);
    }

}
